package com.xsd.awen.utils;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

public class GsonUtils {

    private static Gson GSON;
    static {
        GSON = new GsonBuilder()
                .enableComplexMapKeySerialization()
                .setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")
                .registerTypeAdapter(LocalDateTime.class,new GsonUtils().new LocalDateAdapter())
                .create();
    }

    class LocalDateAdapter implements JsonSerializer<LocalDateTime> {
        @Override
        public JsonElement serialize(LocalDateTime localDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
            return new JsonPrimitive(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
    }

    protected GsonUtils() {
    }

    public static String toJson(Object obj){
        return GSON.toJson(obj);
    }

    public static <T>  T fromJson(String json, Type type){
        return GSON.fromJson(json, type);
    }

    public static <T>  T fromJson(JsonElement jsonElement, Type type){
        return GSON.fromJson(jsonElement, type);
    }

    public static <T>  T fromJson(Map map, Type type){
        return GSON.fromJson(toJson(map), type);
    }

    public static JsonObject fromJson(String json){
        return GSON.fromJson(json, JsonObject.class);
    }

    public static JsonArray toJsonArray(String json){
        return GSON.fromJson(json, JsonArray.class);
    }
}
